package com.qicheng.wlhyspider.tianjin.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qicheng.wlhyspider.common.HttpUtils;
import com.qicheng.wlhyspider.common.PageResult;
import com.qicheng.wlhyspider.common.RedisUtils;
import com.qicheng.wlhyspider.tianjin.dao.TjDriverRepository;
import com.qicheng.wlhyspider.tianjin.entity.TjDriverEntity;
import com.qicheng.wlhyspider.tianjin.mapper.TjDriverMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/tianjin/driver")
@Slf4j
public class TjDriverController {
    private final TjDriverRepository driverRepository;
    private final TjDriverMapper tjDriverMapper;
    private final RedisUtils redisUtils;


    public TjDriverController(TjDriverRepository driverRepository, TjDriverMapper tjDriverMapper, RedisUtils redisUtils) {
        this.driverRepository = driverRepository;
        this.tjDriverMapper = tjDriverMapper;
        this.redisUtils = redisUtils;
    }

    private List<String> tjDriverIdList = new ArrayList<>();

    @GetMapping("/save")
    public String save(@RequestParam("page") Integer page, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
        Long maxPage = 3511L;
        if (CollectionUtil.isEmpty(tjDriverIdList)){
            tjDriverIdList =  tjDriverMapper.selectList(Wrappers.<TjDriverEntity>lambdaQuery()
                    .select(TjDriverEntity::getId)).stream().map(TjDriverEntity::getId).collect(Collectors.toList());
        }

        for (int i = 0; i < 3511; i++) {
            if (i % 10 == 1){
                saveAll(i,  startDate, endDate);
            }

        }
//
//
////        Integer limit = 500;
//        Integer pages = 10;
////        LoginUtils.login();
//        CompletableFuture<Object>[] futures = new CompletableFuture[pages];
//        for (int i = 0; i < pages; i++) {
//            int finalPage = page + i;
//            CompletableFuture<Object> future = CompletableFuture.supplyAsync(() -> {
//                try {
//                    saveAll(finalPage,  startDate, endDate);
//                    log.info("驾驶员插入，第{}页成功", finalPage);
//                } catch (Exception e) {
//                    log.error("驾驶员插入，第{}页失败", finalPage);
//                    log.error(e.getMessage(), e);
//                    e.printStackTrace();
//                }
//                return null;
//            });
//            futures[i] = future;
//        }
//        // todo 最好在循环插入的时候也捕获异常
//        log.info("====futures.length=={}",futures.length);
//        CompletableFuture<Void> cf = CompletableFuture.allOf(futures);
//
//        // 如果执行成功:
//        cf.thenAccept((result) -> {
//            log.info("驾驶员插入成功！！！");
//            if (page < maxPage){
//                save(page + pages,startDate,endDate);
//            }
//
//        });
//        // 如果执行异常:
//        cf.exceptionally((e) -> {
//            e.printStackTrace();
//            log.info("驾驶员插入失败！！！");
//            return null;
//        });
//        // 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:
//        try {
//            Thread.sleep(200);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }



        return "驾驶员插入成功！！！";

    }

    private String saveAll(Integer page, String startDate, String endDate) {
        String url = String.format("http://218.67.246.252:7801/wlhy/notcc.driver/driverinfo/officialList?isOfficial=1&pageNo=%s&pageSize=%s",
                page, 500, startDate, endDate);
        HttpResponse httpResponse = HttpUtils.TjHttpGet(url,redisUtils);
        if (httpResponse.getStatus() == 200) {
            String body = httpResponse.body();
            PageResult pageResult = JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parse(body)), PageResult.class);
            PageResult.ResultDTO result = pageResult.getResult();
            List<TjDriverEntity> list = JSONArray.parseArray(JSONArray.toJSONString(result.getRecords()), TjDriverEntity.class);
            list = list.stream().filter(i -> !tjDriverIdList.contains(i.getId())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(list)){
                tjDriverMapper.insertBatchSomeColumn(list);
            }
            log.info(String.format("驾驶员查询，%s到%s，第%s页，总页数%s",startDate,endDate,page,result.getPages()));
//            if (page < result.getPages()) {
//                page++;
//                return save(page, startDate, endDate);
//            }

        }  else if (httpResponse.getStatus() == 203) {
            log.info("登录信息失效");
//            return "返回：登录信息失效";
//            LoginUtils.login();
            return "登录信息失效";
        } else {
            log.info("查询失败");
            return "返回：查询失败";
        }
        log.info("返回：插入成功");
        return "插入成功";
    }
}
